package com.brid.server;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Properties;

/**
 * @Author: 司军强
 * @Date: 20:24 2019/12/18
 * @Description: 消费者消费消息
 */
@Service
public class KfkaConsumer {

    //监听到的kafka集群地址
    private static final String BROKERLIST = "192.168.223.128:9092";
    //topic 的name
    private static final String TOPIC = "hema";
    //指定消费组
    private static final String groupId = "group.demo";

    /**
     * 定义一个消费者消费生产者生产的消息
     *
     * @param args
     */
    public static void main(String[] args) {
        //基本配置
        Properties properties = new Properties();
        //设置key序列化
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        //设置值反序列器
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        //设置连接地址
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, BROKERLIST);
        //设置组id
        properties.put("group.id", groupId);

//////////////////////////////////////////////////////////////////////////////
        //创建消费者对象
        KafkaConsumer consumer = new KafkaConsumer<>(properties);
        //订阅消息
        consumer.subscribe(Collections.singletonList(TOPIC));

        while (true) {
                //每隔1秒轮询一次
                ConsumerRecords<String, String> records = consumer.poll(Duration.ofMinutes(5000));
                for (ConsumerRecord<String, String> record : records) {
                    System.out.println("record = " + record.value());
                }
            }


        }

    }


